package cn.kimming.wms.web.action;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.interceptor.annotations.InputConfig;

import cn.kimming.wms.anno.RequiredPermission;
import cn.kimming.wms.domain.JsonMsg;
import cn.kimming.wms.domain.Supplier;
import cn.kimming.wms.excep.ObjectIsUsedException;
import cn.kimming.wms.query.QueryObject;
import cn.kimming.wms.service.ISupplierService;
import lombok.Getter;

@Controller("supplierAction")
@Scope("prototype")
public class SupplierAction extends BaseAction {
	
	private static final long serialVersionUID = -8784596193420730799L;

	@Autowired
	private ISupplierService supplierService;
	
	@Getter
	private Supplier supplier = new Supplier();
	
	@Getter 
	private QueryObject qo = new QueryObject();

	@Override
	@RequiredPermission("供应商列表")
	@InputConfig(methodName="input")
	public String execute() {
		try {
			ActionContext.getContext().put("objs", supplierService.query(qo));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return LIST;
	}
	
	@RequiredPermission("供应商编辑")
	public String input() {
		try {
			if (supplier.getId() != null) {
				supplier = supplierService.get(supplier.getId());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return INPUT;
	}

	@RequiredPermission("供应商保存和更新")
	public String saveOrUpdate() {
		if (supplier.getId() != null) {
			try {
				supplierService.update(supplier);
				addActionMessage("更新成功!");
			} catch(Exception e) {
				e.printStackTrace();
				addActionError("系统异常,保存失败!");
			}
		} else {
			try {
				supplierService.save(supplier);
				addActionMessage("保存成功!");
			} catch(Exception e) {
				e.printStackTrace();
				addActionError("系统异常,保存失败!");
			}
		}
		return SUCCESS;
	}

	@RequiredPermission("供应商删除")
	public String delete() {
		try {
			if (supplier.getId() != null) {
				supplierService.delete(supplier.getId());
				putJSON(new JsonMsg(true, "删除成功!"));
			}
		} catch(ObjectIsUsedException e) {
			e.printStackTrace();
			putJSON(new JsonMsg(false, e.getMessage()));
			
		}catch (Exception e) {
			e.printStackTrace();
			putJSON(new JsonMsg(false, "系统异常,删除失败!"));
		}
		return NONE;
	}
	
	public void prepareSaveOrUpdate() throws Exception {
		if (supplier.getId() != null) {
			supplier = supplierService.get(supplier.getId());
		}
	}
	
}
